using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;

public partial class AddBooks : System.Web.UI.Page
{
	protected string myIsbn, myAuthor, myTitle, myPublisher, myLanguage;
    protected int myNumber;

    protected void Page_Load(object sender, EventArgs e)
    {
        
    }

    protected void addButton_Click(object sender, System.EventArgs e)
    {
        try
        {
            myIsbn = ((TextBox)this.LoginViewAdmin.FindControl("bookIsbn")).Text;
            if (myIsbn == "")
            {
                ((Label)this.LoginViewAdmin.FindControl("errorLabel")).Text =
                    "Please provide a ISBN or ID number to identify the book.";
                return;
            }
            myTitle = ((TextBox)this.LoginViewAdmin.FindControl("bookTitle")).Text;
            myAuthor = ((TextBox)this.LoginViewAdmin.FindControl("bookAuthor")).Text;
            myPublisher = ((TextBox)this.LoginViewAdmin.FindControl("bookPublisher")).Text;
            myLanguage = ((TextBox)this.LoginViewAdmin.FindControl("bookLanguage")).Text;
            string bookNumberText = ((TextBox)this.LoginViewAdmin.FindControl("bookNumber")).Text.Trim();
            if(bookNumberText != "")
                myNumber = Convert.ToInt32(((TextBox)this.LoginViewAdmin.FindControl("bookNumber")).Text);
            else
                myNumber = 1;
            SqlConnection connection = 
                new SqlConnection(ConfigurationManager.ConnectionStrings["sylib"].ConnectionString);
            connection.Open();
            string sCommand = "INSERT INTO books(bookid,title,author,publisher,language,number,requested) VALUES( '" +
                myIsbn.Replace("'", "''") + "','" + myTitle.Replace("'", "''") + "','" + myAuthor.Replace("'", "''") +
                "','" + myPublisher.Replace("'", "''") + "','" + myLanguage.Replace("'", "''") + "', '" + myNumber +
                "', '0')";
            SqlCommand cmd = new SqlCommand(sCommand,connection); 
            cmd.ExecuteNonQuery();
            connection.Close();
            ((Label)this.LoginViewAdmin.FindControl("errorLabel")).Text = "Book Added!";
            ((TextBox)this.LoginViewAdmin.FindControl("bookIsbn")).Text = "";
            ((TextBox)this.LoginViewAdmin.FindControl("bookTitle")).Text = "";
            ((TextBox)this.LoginViewAdmin.FindControl("bookAuthor")).Text = "";
            ((TextBox)this.LoginViewAdmin.FindControl("bookPublisher")).Text = "";
            ((TextBox)this.LoginViewAdmin.FindControl("bookLanguage")).Text = "";
            ((TextBox)this.LoginViewAdmin.FindControl("bookNumber")).Text = "";
        }
        catch (System.Data.SqlClient.SqlException err) 
        {
            if (err.ErrorCode == -2146232060) // This code indicates that the book is already in the database.
            {
                ((Label)this.LoginViewAdmin.FindControl("errorLabel")).Text =
                    "Book not added, it's already in the database. To increase the quantity of this book use Manage Books.";
                return;
            }

            ((Label)this.LoginViewAdmin.FindControl("errorLabel")).Text =
                "Book not added, the system failed to add it.";
            ((Label)this.LoginViewAdmin.FindControl("errorLabel")).Text = 
                ((Label)this.LoginViewAdmin.FindControl("errorLabel")).Text + "\n\n" + err.ToString();
        }
    }

    protected void fetchBtn_Click(object sender, EventArgs e)
    {
		try 
		{
            string stripHtmlRegex = "<[^<>]+>"; // Does not consider comments. Very simple html tag strip.

            ((Button)this.LoginViewAdmin.FindControl("fetchBtn")).Enabled = false;
            System.Net.WebClient client = new System.Net.WebClient();
            //myIsbn = "0316769487";
            myIsbn = ((TextBox)this.LoginViewAdmin.FindControl("bookIsbn")).Text.Replace(" ", "");
            myIsbn = myIsbn.Replace("-", "");
            ((TextBox)this.LoginViewAdmin.FindControl("bookIsbn")).Text = myIsbn;

            // Initialize data
            myPublisher = "not found";
            myTitle = "not found";
            myAuthor = "not found";
            string bookInfoFetchDataFile = ConfigurationManager.AppSettings.Get("bookInfoFetchDataFile");

            bookInfoFetchDataFile = MapPath(bookInfoFetchDataFile);

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.Load(bookInfoFetchDataFile);
            bool titleFound = false, authorFound = false, publisherFound = false;
            foreach (System.Xml.XmlElement site in doc.SelectNodes("/BookSites/Site"))
            {
                // Get patterns
                string urlFormat = site.SelectSingleNode("UrlFormat").InnerText;
                string titleAuthorPattern = site.SelectSingleNode("TitleAuthorPattern").InnerText;
                string publisherPattern = site.SelectSingleNode("PublisherPattern").InnerText;
                // Get page
                byte[] buffer = client.DownloadData(string.Format(urlFormat, myIsbn));
                Encoding encoding = Encoding.GetEncoding("iso8859-1");
                string htmlDoc = encoding.GetString(buffer);
                // Match patterns
                Match titleAuthorInfo = Regex.Match(htmlDoc, titleAuthorPattern, RegexOptions.Singleline | RegexOptions.ExplicitCapture);
                Match publisherInfo = Regex.Match(htmlDoc, publisherPattern, RegexOptions.Singleline | RegexOptions.ExplicitCapture);

                if (titleAuthorInfo.Success)
                {
                    if (!titleFound)
                    {
                        myTitle = titleAuthorInfo.Groups["title"].Value.Trim();
                        if (!string.IsNullOrEmpty(myTitle))
                        {
                            myTitle = Regex.Replace(myTitle, stripHtmlRegex, "");
                            titleFound = true;
                        }
                    }
                    if (!authorFound)
                    {
                        myAuthor = titleAuthorInfo.Groups["name"].Value.Trim();
                        if (!string.IsNullOrEmpty(myAuthor))
                        {
                            myAuthor = Regex.Replace(myAuthor, stripHtmlRegex, "");
                            authorFound = true;
                        }

                    }
                }

                if (publisherInfo.Success)
                {
                    if (!publisherFound)
                    {
                        myPublisher = publisherInfo.Groups["publisher"].Value.Trim();
                        if (!string.IsNullOrEmpty(myPublisher))
                        {
                            myPublisher = Regex.Replace(myPublisher, stripHtmlRegex, "");
                            publisherFound = true;
                        }
                    }
                }
                if (titleFound && authorFound && publisherFound)
                {
                    break;
                }
            }


            ((TextBox)this.LoginViewAdmin.FindControl("bookPublisher")).Text = myPublisher;
            ((TextBox)this.LoginViewAdmin.FindControl("bookTitle")).Text = myTitle;
            ((TextBox)this.LoginViewAdmin.FindControl("bookAuthor")).Text = myAuthor;
            ((Button)this.LoginViewAdmin.FindControl("fetchBtn")).Enabled = true;
		}
		catch(System.Net.WebException err) 
		{
            ((Label)this.LoginViewAdmin.FindControl("errorLabel")).Text = 
                "There was an error with the fetch service.  Try again or enter data manually.";
            ((Button)this.LoginViewAdmin.FindControl("fetchBtn")).Enabled = true;
		}
    }
}